package com.nondo.rdp.finance.endpoint.api.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nondo.rdp.auth.common.RoleUtils;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.CourseBuy;
import com.nondo.rdp.finance.domain.course.CourseRate;
import com.nondo.rdp.finance.model.Version;
import com.nondo.rdp.finance.model.course.CourseBean;
import com.nondo.rdp.finance.model.course.CourseEdit;
import com.nondo.rdp.finance.model.course.CourseQuery;
import com.nondo.rdp.finance.service.course.CourseBuyService;
import com.nondo.rdp.finance.service.course.CourseRateService;
import com.nondo.rdp.finance.service.course.CourseService;

@RestController("apiAdminCourse")
@RequestMapping("/api/admin/course")
public class CourseEndpoint {
    @Autowired
    CourseService courseService;
    
    @Autowired
    CourseRateService courseRateService;
    
    @Autowired
    CourseBuyService courseBuyService;

    /**
     * 获取课程详情
     * @param request
     * @param response
     * @param id
     * @param version
     * @return
     */
    @RequestMapping("/info/{id}")
    public View<CourseBean> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id, @RequestBody Version version) {
        View<CourseBean> view = new View<CourseBean>(20000, "获取数据成功");

        CourseBean cousreBean = null;
        Course course = courseService.findOne(id);
        if (course != null) {
            cousreBean = CourseBean.covert2Bean(course);
        } else {
        	cousreBean = new CourseBean();
        }

        view.setData(cousreBean);
        
        return view;
    }

    /**
     * 获取课程列表
     * @param request
     * @param response
     * @param query
     * @return
     */
    @RequestMapping("/list")
    public View<Page<CourseQuery>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Course> query) {
        View<Page<CourseQuery>> view = new View<Page<CourseQuery>>(20000, "获取列表成功");

        Course course = query.getData();
        User user = UserUtils.getUser(request, response);
        
        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
			if (course == null) {
				course = new Course();
			}
			//课程发布者只能查询自己发布的课程
			course.setUser(user);
		}

        Page<Course> page = courseService.findAllForAdmin(new Page<Course>(query.getPage(), query.getSize()), course);
        
        Page<CourseQuery> resultPage = page.convertPage(new ConvertCall<Course, Page<CourseQuery>>() {

			@Override
			public Page<CourseQuery> execute(Page<Course> srcPage) {
				Page<CourseQuery> courseQueryPage = new Page<CourseQuery>(srcPage.getPageNumber(),srcPage.getPageSize(),srcPage.getTotalPages(),srcPage.getTotalElements());
				List<CourseQuery> courseQueryList = new ArrayList<CourseQuery>();
				List<Course> courseList = srcPage.getContent();
				for(Course course : courseList) {
					CourseQuery courseQuery = CourseQuery.covert2Bean(course);
					courseQueryList.add(courseQuery);
				}
				courseQueryPage.setContent(courseQueryList);
				return courseQueryPage;
			}
        	
		});

        view.setData(resultPage);

        return view;
    }

    /**
     * 添加课程
     * @param request
     * @param response
     * @param course
     * @param result
     * @return
     */
    @RequestMapping("/add")
    public View add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Course course, BindingResult result) {
        View view = new View(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
        	User user = UserUtils.getUser(request, response);
        	course.setUser(user);
        	if(course.getRecommend()==null){
        		course.setRecommend(0);
        	}
        	course.setReadNum(0L);
        	course.setStatus(0);
        	course.setHome(0);
        	Date nowDate = new Date();
        	Date publishDate = course.getPublishDate();
			if (publishDate == null) {
				course.setPublishDate(nowDate);
			} else if (publishDate.getTime() - nowDate.getTime() > 0) {
				course.setStatus(0);
			}
            this.courseService.save(course);
        }
        return view;
    }

    /**
     * 修改课程
     * @param request
     * @param response
     * @param course
     * @param result
     * @return
     */
    @RequestMapping("/update")
    public View update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CourseEdit course, BindingResult result) {
        View view = new View(20000, "更新成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
        	User user = UserUtils.getUser(request, response);
        	Course courseDb = this.courseService.findOne(course.getId());
    		if (!user.getId().equals(courseDb.getUser().getId())) {
    			return View.ofError("对不起，你没有权限进行操作");
    		}
    		BeanUtils.copy(course, courseDb);
    		courseDb.setAuditStatus(0);
    		Date nowDate = new Date();
        	Date publishDate = course.getPublishDate();
			if (publishDate == null) {
				course.setPublishDate(nowDate);
			} else if (publishDate.getTime() - nowDate.getTime() > 0) {
				course.setStatus(0);
			}
            this.courseService.update(courseDb);
        }

        return view;
    }

    /**
     * 删除课程
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");
        User user = UserUtils.getUser(request, response);
        Course courseDb = this.courseService.findOne(id);
		if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)
				&& !user.getId().equals(courseDb.getUser().getId())) {
			return View.ofError("对不起，你没有权限进行操作");
		}
		this.courseService.delete(id);
        return view;
    }

    /**
     * 课程评分
     * @param request
     * @param response
     * @param courseRate
     * @return
     */
    @RequestMapping("/rate")
    public View<CourseRate> rate(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CourseRate courseRate) {
		View<CourseRate> view = new View<CourseRate>(20000, "打分成功");
		User user = UserUtils.getUser(request, response);
		Course course = this.courseService.findOne(courseRate.getCourseId());
		CourseRate courseRateDb = this.courseRateService.check(course.getId(),user.getId());
		if (courseRateDb != null) {
			view.setCode(3000);
			view.setMessage("您已经给该课程打过分啦");
			return view;
		}
		courseRate.setCourse(course);
		courseRate.setRateUser(user);
		this.courseRateService.save(courseRate);
		return view;
    }

    /**
     * 购买课程
     * @param request
     * @param response
     * @param course
     * @param result
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/buy")
    public View buy(HttpServletRequest request, HttpServletResponse response, @RequestBody Course course, BindingResult result) {
    	View view = new View(20000, "购买成功");
		
		User user = UserUtils.getUser(request, response);
		course = this.courseService.findOne(course.getId());
		if (course == null) {
			view.setCode(50000);
			view.setMessage("课程不存在或者已删除");
			return view;
		}
		int isBuy = this.courseBuyService.getOne(course.getId(), user.getId());
		if (isBuy == 0) {
			CourseBuy courseBuy = new CourseBuy();
			courseBuy.setCourse(course);
			courseBuy.setUser(user);
			this.courseBuyService.save(courseBuy);
		} else {
			view.setCode(50000);
			view.setMessage("用户已购买过此课程");
			return view;
		}
		
		return view;
    }

    /**
     * 已购课程列表
     * @param request
     * @param response
     * @param query
     * @return
     */
    @RequestMapping("/buy/list")
    public View<Page<CourseQuery>> buyList(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Course> query) {
        View<Page<CourseQuery>> view = new View<Page<CourseQuery>>(20000, "获取列表成功");

        Course course = query.getData();

        User user = UserUtils.getUser(request, response);
        
        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
			if (course == null) {
				course = new Course();
			}
			//课程发布者只能查询自己发布的课程
			course.setUser(user);
		}

        Page<CourseBuy> page = courseBuyService.findAll(new Page<CourseBuy>(query.getPage(), query.getSize()), course);
        
        Page<CourseQuery> resultPage = page.convertPage(new ConvertCall<CourseBuy, Page<CourseQuery>>() {

			@Override
			public Page<CourseQuery> execute(Page<CourseBuy> srcPage) {
				Page<CourseQuery> courseQueryPage = new Page<CourseQuery>(srcPage.getPageNumber(),srcPage.getPageSize(),srcPage.getTotalPages(),srcPage.getTotalElements());
				List<CourseQuery> courseQueryList = new ArrayList<CourseQuery>();
				List<CourseBuy> courseBuyList = srcPage.getContent();
				for(CourseBuy courseBuy : courseBuyList) {
					Course course = courseService.findOne(courseBuy.getCourse().getId());
					CourseQuery courseQuery = CourseQuery.covert2Bean(course);
					courseQueryList.add(courseQuery);
				}
				courseQueryPage.setContent(courseQueryList);
				return courseQueryPage;
			}
        	
		});

        view.setData(resultPage);

        return view;
    }

    /**
     * 审核课程
     * @param request
     * @param response
     * @param courseBean
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/audit")
    public View audit(HttpServletRequest request, HttpServletResponse response, @RequestBody CourseBean courseBean) {
        View view = new View(20000, "操作成功");

    	Course courseDb = this.courseService.findOne(courseBean.getId());
		courseDb.setAuditStatus(courseBean.getAuditStatus());
        this.courseService.update(courseDb);

        return view;
    }

    /**
     * 上下架课程
     * @param request
     * @param response
     * @param courseBean
     * @return
     */
    @RequestMapping("/OnAndOff")
    public View OnAndOff(HttpServletRequest request, HttpServletResponse response, @RequestBody CourseBean courseBean) {
        View view = new View(20000, "操作成功");
        User user = UserUtils.getUser(request, response);
    	Course courseDb = this.courseService.findOne(courseBean.getId());
    	if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)
				&& !user.getId().equals(courseDb.getUser().getId())) {
			return View.ofError("对不起，你没有权限进行操作");
		}
    	courseDb.setStatus(courseBean.getStatus());
        this.courseService.update(courseDb);

        return view;
    }
    
}